﻿/*
 * 独立的上传文件页面。 2009-5-11
 * 可用于弹出窗口上传文件。
 * 
 * 
 * 
 * **/
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Brettle.Web.NeatUpload;
using System.Collections.Generic;
using System.IO;
using EQT.Model;
using EQT.Dal;

public partial class uploadfile2 : IUploadPage
{
    private DaTfile datfile = new DaTfile(DaCommon.DefaultDb);


    /// <summary>
    /// 需回调的父窗体控件ID，会调用此控件上的click方法。
    /// </summary>
    private string parentCallBackControlId;

    public string ParentCallBackControlId
    {
        get { return parentCallBackControlId; }
        set { parentCallBackControlId = value; }
    }
    
    protected void Page_Load(object sender, EventArgs e)
    {
       
         
        if (!Page.IsPostBack)
        {
            string m = Request.QueryString["m"];
            #region 根据是多文件上传还是单文件上传来决定页面按钮
            if (!String.IsNullOrEmpty(m) && m.Trim().Equals("1")) //多文件
            {
               
                multiFileId2.Visible = true;
                btnUploadMulti.Visible = true;

                
                inputFileId1.Visible = false;
                btnUpload1.Visible = false;
                
            }
            else //单个
            {
                btnUploadMulti.Visible = false;
                multiFileId2.Visible = false;

                btnUpload1.Visible = true;
                inputFileId1.Visible = true;
            }
            //TODO:查询字符串应该加密
            #endregion

            string upload_mode = Request.QueryString[null];
            parentCallBackControlId = Request.QueryString["pccid"];

            if (upload_mode == null || parentCallBackControlId==null)
            {
                Utility.SiteError(String.Format("缺失必须的参数upload_mode={0},parentCallBackControlId={1}!",upload_mode,parentCallBackControlId), Response);
            }
            else
            {
                IUploadFile uf= UploadFileFactory.GetUF(upload_mode);
                if (uf != null)
                {
                    ViewState["UPLOAD_MODE"] = upload_mode;
                    uf.InitUpload(this, Request.QueryString);
                }
                else
                {
                    Utility.SiteError("未知的文档上传请求:"+upload_mode, Response);
                }               
             
            }
        }
        
    }

    protected void btnUpload1_Click(object sender, EventArgs e)
    {
        if (this.IsValid && inputFileId1.HasFile)
        {
            #region 处理上传的文件 构建一个MoTfile对象
            string file_id = SequenceKeys.GenerateFileID();
            //写到本地时的全路径，用URL表达
            string localpath = System.IO.Path.Combine(SiteConfig.File_Repository_Location,
                file_id + System.IO.Path.GetExtension(inputFileId1.FileName));
            //inputFileId1.MoveTo(localpath, MoveToOptions.Overwrite);
            MoTfile motfile = new MoTfile();
            motfile.File_Id = file_id;
            motfile.File_Length = inputFileId1.FileContent.Length;
            motfile.File_Name = inputFileId1.FileName; //原始文件的名称，含扩展名，不含路径    
            motfile.File_Url = Utility.GetUri4LocalFile(localpath);

            using (inputFileId1.FileContent)
            {
                using (System.IO.FileStream sw = new FileStream(localpath, FileMode.Create))
                {
                    Utility.CopyStream(inputFileId1.FileContent, sw);
                    sw.Close();
                }
                inputFileId1.FileContent.Close();
            }
            #endregion

            UserContext uc = Session["USER_CONTEXT"] as UserContext;

            string upload_mode = ViewState["UPLOAD_MODE"].ToString();
            IUploadFile uf = UploadFileFactory.GetUF(upload_mode);
            uf.Upload1(this, motfile,uc.UserID);           
            inputFileId1.Dispose();
        }
    }

    /// <summary>
    /// 一个实体关联多个文档时
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnUploadMulti_Click(object sender, EventArgs e)
    {
        if (multiFileId2.Files.Length > 0)
        {
            UserContext uc = Session["USER_CONTEXT"] as UserContext;
            List<MoTfile> fileList = new List<MoTfile>(multiFileId2.Files.Length);
            List<MoDirFile> dfList = new List<MoDirFile>(multiFileId2.Files.Length);

            uploadPre.InnerText += "批次上传 " + multiFileId2.Files.Length + " 文件:\n";
            foreach (UploadedFile file in multiFileId2.Files)
            {
                string file_id = SequenceKeys.GenerateFileID();
                //写到本地时的全路径，用URL表达
                string localpath = System.IO.Path.Combine(SiteConfig.File_Repository_Location,
                    file_id + System.IO.Path.GetExtension(file.FileName));
                try
                {
                    using (file.InputStream)
                    {
                        using (FileStream fs = new FileStream(localpath, FileMode.Create))
                        {
                            Utility.CopyStream(file.InputStream, fs);
                            fs.Flush();
                        }
                        file.InputStream.Close();
                    }
                    //file.MoveTo(localpath, MoveToOptions.Overwrite);
                }
                catch (SystemException se)
                {
                    Utility.GlobalLog.Error("上传文件失败！", se);
                    uploadPre.InnerText += Environment.NewLine + String.Format("上传文件【{0}】失败！", file.FileName) + Environment.NewLine + se.Message;
                    break;
                }

                MoDirFile modf = new MoDirFile();
                modf.Df_Id = file_id;
                modf.Df_Name = file.FileName;
                modf.Df_Flag = "F";
                //Note:批次上传只针对文档管理
                modf.Parent_Did = ViewState["DIRID"].ToString();
                modf.Uid = uc.UserID;

                MoTfile motfile = new MoTfile();
                motfile.File_Id = file_id;
                motfile.File_Length = file.ContentLength;
                motfile.File_Name = file.FileName; //原始文件的名称，含扩展名，不含路径    
                motfile.File_Url = Utility.GetUri4LocalFile(localpath);

                fileList.Add(motfile);
                dfList.Add(modf);
                uploadPre.InnerText += file.FileName + "\n";
            }
            try
            {
                datfile.AddFileEx(dfList, fileList);
            }
            catch (DalException de)
            {
                Utility.GlobalLog.Error("批量添加文件失败!", de);
                Utility.SiteError("批量添加文件失败!" + de.Message, Response);
            }



        }
    }
    

    public override void SetPageTitle(string title)
    {
        labelUploadContext.Text = Server.HtmlEncode(title);
    }
}
